<?php
/**
 * 粉丝模块
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\util\WechatThirdUtil;
use app\common\model\WxUser;
use app\common\model\Users as UsersModel;
use think\Db;
use think\Session;

class Fans extends AdminBase
{
    protected $wechat_obj;
    protected $config;
    protected $author_config;
    protected $wx_user_model;
    protected $users_model;

    protected function _initialize(){
        parent::_initialize();
        $this->wx_user_model = new WxUser;
        $this->users_model = new UsersModel;
        $this->config = $this->wx_user_model->find();
        $this->author_config = session::get('wechat_info');
        $this->wechat_obj = new WechatThirdUtil($this->config , $this->author_config);
    }

    /*
     * 获取当前公众号下面的粉丝数据
     * */
    public function index(){
        return $this->fetch();
    }

    public function allfans($start_time = '',$end_time = '',$page = 1,$keyword = ''){
        $count = '';
        $where = [];
        if(!empty($start_time) && !empty($end_time)){
            $where = [
                'subscribe_time'=>['between',[$start_time,$end_time]],
            ];
        }
        if (!empty($keyword)) {
            $where['think_users.nickname'] = ['like','%'.$keyword.'%'];
        }
        $where['think_users.auid'] = ['eq',$this->author_config['id']];
        $count = Db::name('users')
            ->field('COUNT(*) total,COUNT(CASE WHEN subscribe = 1 THEN 1 ELSE NULL END) subscount,COUNT(CASE WHEN subscribe = 0 THEN 1 ELSE NULL END ) un_subscount,COUNT(CASE WHEN repeat_subscribe = 1 && subscribe = 1 THEN 1 ELSE NULL END) repeat_subscribe_count,COUNT(CASE WHEN is_second_unsubscribe = 1 THEN 1 ELSE NULL END) as second_unsubscribe_count')
            ->where($where)
            ->select();//关注人数

        $result = $this->users_model
            ->field('u.butt_id,u.user_id,u.auid,u.sex,u.subscribe_time,u.unsubscribe_time,u.subscribe,u.openid,u.headimgurl,u.nickname,think_csuser.nickname as cs_nickname')
            ->alias('u')
            ->join('think_csuser','u.butt_id = think_csuser.id','left')
            ->where($where)
            ->order('subscribe_time desc')
            ->paginate(15,false,['page'=>$page]);

        foreach($result as $v){
            $map = [
                'openid' => ['eq',$v['openid']],
                'cs_id' => ['eq',$v['butt_id']]
            ];
            $v['chat_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->group('send_type')->column('send_type,count(*) as chat_count');
        }

        //统计菜单栏点击数
        $click_count = Db::name('wechat_menu_click')->where('auid',$this->author_config['id'])->count();
       return $this->fetch(
           'allfans',[
               'allfans'=>$result,
                'keyword'=> $keyword
           ]
       );
    }

    /*
     *
     * */
    public function chat(){
        return $this->fetch();
    }

    /**
     * 获取粉丝列表 获取公众号上的粉丝列表
     */
    public function getFansList(){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getFanIdList();
        return json($result);
    }

    public function updateFansInfo(){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getFanIdList('ovBM91UgMUBxp8pGhu05PPW-rJcg');
        $openids = $result['data']['openid'];

        foreach($openids as $v){
            $wxdata = $wechat_obj->getFanInfo($v);
            $user = [
                'openid'    => $v,
                'auid'      => $this->author_config['id'],
                'headimgurl'  => isset($wxdata['headimgurl']) ? $wxdata['headimgurl'] : '',
                'nickname'  => isset($wxdata['nickname']) ? $wxdata['nickname'] : '微信用户',
                'sex'       => isset($wxdata['sex']) ? $wxdata['sex'] : 0,
                'subscribe' => isset($wxdata['subscribe']) ? $wxdata['subscribe'] : 0,
                'oauth'     => 'weixin',
                'subscribe_time'  => isset($wxdata['subscribe_time']) ? $wxdata['subscribe_time'] : time(),
                'token'     => md5(time().mt_rand(1,99999)),
                'password'  => '',
                'is_distribut' => 1,
            ];
            isset($wxdata['unionid']) && $user['unionid'] = $wxdata['unionid'];
            $ret = Db::name('users')->insert($user);
            if(!$ret){
                echo '失败';exit();
            }
        }
    }

/*  id,auid group_id name sort pid remark color
 * CREATE TABLE `think_user_group` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '分类ID',
  `auid` int(11) NOT NULL COMMENT '授权公众号id',
  `group_id` int(11) DEFAULT NULL COMMENT '标签id',
  `name` varchar(50) NOT NULL COMMENT '分类名称',
  `sort` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '排序',
  `pid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '上级分类ID',
  `create_time` datetime NOT NULL,
  `remark` varchar(255) DEFAULT NULL,
  `color` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=135 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='分类表';

 * */


    /**
     * 获取数据库粉丝列表
     */
    public function getFansDetailList($start_time = '',$end_time = '',$page = 1){
        $count = '';
        $where = [];
        if(!empty($start_time) && !empty($end_time)){
            $where = [
                'subscribe_time'=>['between',[$start_time,$end_time]],
            ];
        }
        $where['think_users.auid'] = ['eq',$this->author_config['id']];
        $count = Db::name('users')
                ->field('COUNT(*) total,COUNT(CASE WHEN subscribe = 1 THEN 1 ELSE NULL END) subscount,COUNT(CASE WHEN subscribe = 0 THEN 1 ELSE NULL END ) un_subscount,COUNT(CASE WHEN repeat_subscribe = 1 && subscribe = 1 THEN 1 ELSE NULL END) repeat_subscribe_count,COUNT(CASE WHEN is_second_unsubscribe = 1 THEN 1 ELSE NULL END) as second_unsubscribe_count')
                ->where($where)
                ->select();//关注人数
        $result = $this->users_model
                ->field('u.butt_id,u.sex,u.subscribe_time,u.unsubscribe_time,u.subscribe,u.openid,u.headimgurl,u.nickname,think_csuser.nickname as cs_nickname')
                ->alias('u')
                ->join('think_csuser','u.butt_id = think_csuser.id','left')
                ->where($where)
                ->order('subscribe_time desc')
                ->paginate(15,false,['page'=>$page]);

        foreach($result as $v){
            $map = [
                'openid' => ['eq',$v['openid']],
                'cs_id' => ['eq',$v['butt_id']]
            ];
            $v['chat_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->group('send_type')->column('send_type,count(*) as chat_count');
        }

        //统计菜单栏点击数
        $click_count = Db::name('wechat_menu_click')->where('auid',$this->author_config['id'])->count();
        
        return json(['result'=>$result,'count'=>$count[0],'click_count' => $click_count]);
    }

    /**
     * 新建标签
     * @param type tag
     */
    public function addFansTag(){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(isset($data['tag']) == false && empty($data['tag'])){
                return false;
            }
            $tag = $data['tag'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->createTag($tag);
    
            return json($result);
        }
    }

    /**
     * 获取公众号已创建的标签
     */
    public function getAllFansTag(){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getAllFanTags();
        return json($result);
    }

    /**
     * 编辑标签
     * @param type $id
     * @param type $tag
     */
    public function editFansTag(){
        if($this->request->isPost()){
            $data = $this->request->post();

            if(isset($data['id']) == false && isset($data['tag']) == false){
    
                return json(['msg'=>'参数错误']);
    
            }else if(empty($data['tag'])){
    
                return json(['msg'=>'标签不能为空']);
    
            }
    
            $id = $data['id'];
            $tag = $data['tag'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->updateTag($id,$tag);
            return json($result);
        }
    }

    /**
     * 删除标签
     * @param type $id
     * @return boolean
     */
    public function deleteFansTag(){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(isset($data['id']) == false){
                return json(['msg'=>'参数错误']);
            }
            $id = $data['id'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->deleteTag($id);
            return json($result);
        }
    }

    /**
     * 获取标签下粉丝列表
     */
    public function getTagFansList($tagid,$next_openid = ''){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getTagUsersList($tagid,$next_openid);
        return json($result);
    }

    /**
     * 批量为用户打标签
     * @param array $openid_list
     * @param int $tagid
     * @return boolean
     */
    public function addsFansTags(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $openid_list = $data['openid_list'];
            $tagid = $data['tagid'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->batchUsersTag($tagid,$next_openid);
            return json($result);
        }
    }

    /**
     * 批量为用户取消标签
     * @param array $openid_list
     * @param int $tagid
     * @return boolean
     */
    public function deletesFansTags(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $openid_list = $data['openid_list'];
            $tagid = $data['tagid'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->batchCancelUsersTag($tagid,$next_openid);
            return json($result);
        }
    }

    /**
     * 获取用户身上的标签列表
     * @param type $openid
     * @return array
     */
    public function getFansTagsDetail(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $openid = $data['openid'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->getUserTags($openid);
            return json($result);
        }
    }

    /**
     * 足迹
     */
    public function queryFootPrint($openid){
        $result = Db::name('footprint')->where('openid',$openid)->select();
        return json($result);
    }


}